package org.realteam.iframework.json;

import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;

import org.junit.Test;
import org.realteam.iframework.json.beans.MyBean;

/**
 * @author zhangxf
 * @version 1.0
 * @create on : 2012-2-14 下午02:30:20
 *
 */

/**
 * 
 * The simplest way to create a JSONObject from a bean or Map is through the
 * static factory methods from JSONObject. JSONObject.fromObject() will inspect
 * its parameter and call the correct factory or constructor.
 * 
 */
public class BeanMap2JSON {

	@Test
	public void testMap2JSON() {
		Map map = new HashMap();
		map.put("name", "json");
		map.put("bool", Boolean.TRUE);
		map.put("int", new Integer(1));
		map.put("arr", new String[] { "a", "b" });
		map.put("func", "function(i){ return this.arr[i]; }");

		JSONObject jsonObject = JSONObject.fromObject(map);
		System.out.println(jsonObject);// prints ["name":"json","bool":true,"int":1,"arr":["a","b"],"func":function(i){ return this.arr[i]; }]  
		System.out.println(jsonObject.get("arr"));
	}
	
	@Test
	public void testBean2JSON() {
		JSONObject jsonObject = JSONObject.fromObject( new MyBean() );   
		System.out.println( jsonObject );   
		/* prints  
		  {"name":"json","pojoId":1,"options":["a","f"],  
		  "func1":function(i){ return this.options[i];},  
		  "func2":function(i){ return this.options[i];}}  
		*/ 
	}

}
